package com.p2p.auth.service.specification;


import com.p2p.auth.domain.entity.User;
import com.p2p.auth.domain.dto.user.UserQueryDTO;
import org.hibernate.annotations.common.util.StringHelper;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

/**
 * @author Evan
 * @date 2018/2/12
 */
public class UserSpecification {
    public static Specification<User> buildFromDTO(UserQueryDTO dto){
        return (root, query, builder) -> {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfmat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            ArrayList<Predicate> list = new ArrayList<>();

            if (StringHelper.isNotEmpty(dto.getRealName())) {
                list.add(builder.like(root.get("realName"), "%" + dto.getRealName() + "%"));
            }

            if (StringHelper.isNotEmpty(dto.getPhoneNum())) {
                list.add(builder.like(root.get("phoneNum"), "%" + dto.getPhoneNum() + "%"));
            }

            if (StringHelper.isNotEmpty(dto.getRetailersName())) {
                list.add(builder.equal(root.get("retailersName"), "%" + dto.getRetailersName() + "%"));
            }

            if (StringHelper.isNotEmpty(dto.getRegistQueryStart())
                    ||  StringHelper.isNotEmpty(dto.getRegistQueryEnd())) {
                String startDay = "2018-01-01";
                String endDay = "2030-01-01";
                if(StringHelper.isNotEmpty(dto.getRegistQueryStart())){
                    startDay = dto.getRegistQueryStart();
                }

                if(StringHelper.isNotEmpty(dto.getRegistQueryEnd())){
                    endDay = dto.getRegistQueryEnd();
                }

                try {
                    list.add(builder.between(root.get("dateCreated"),
                            sdfmat.parse(sdfmat.format(sdf.parse(startDay).getTime())),
                            sdfmat.parse(sdfmat.format(sdf.parse(endDay).getTime() + 86400000))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }

            Predicate[] predicates = new Predicate[list.size()];
            predicates = list.toArray(predicates);

            return builder.and(predicates);
        };
    }
}
